package org.grow.leavejpa.service;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.grow.leavejpa.dao.UserInfoJpa;
import org.grow.leavejpa.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-6-7
 */
@Service
public class AuthHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

    @Autowired
    UserInfoJpa userInfoJpa;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        System.out.println(e.getClass()+"  ==>  "+e.getMessage());
        if (e instanceof BadCredentialsException){
            response.setStatus(960);
            response.getWriter().println(e.getMessage()+":::");

        }else if(e instanceof DisabledException){
            response.setStatus(961);
            response.getWriter().println(e.getMessage()+"|||");
        }else {
            response.setStatus(962);
            response.getWriter().println(e.getMessage());
        }
//        response.setStatus(403);
//        DisabledException
    }

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("成功登录： "+authentication.getPrincipal());
        response.setStatus(200);
        UserInfo principal = (UserInfo) authentication.getPrincipal();
//        object mapper
//       java object -> json string
//        response.setCharacterEncoding("utf8");
        response.getWriter().println(
                objectMapper.writeValueAsString(principal)
        );
        response.flushBuffer();

        principal.setLastLoginTime(LocalDateTime.now());
        userInfoJpa.save(principal);

    }
}
